# !/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd

if __name__ == '__main__':
    data = [
        ['wind', '羽毛球', 3],
        ['wind', '篮球', 5],
        ['wind', '足球', 5],
        ['wind', '兵乓球', 1],
        ['cc', '足球', 7],
        ['cc', '兵乓球', 5],
        ['cc', '篮球', 5],
        ['cc', '羽毛球', 3],
        ['cc', '棒球', 3],
        ['cc', '台球', 7],
        ['aa', '棒球', 5],
        ['aa', '篮球', 5],
        ['dd', '羽毛球', 5],
        ['dd', '篮球', 5],
    ]
    df = pd.DataFrame(data, columns=["名称", "爱好", "喜爱程度"])
    print(df)

    print("-----------------------------基于用户的协同过滤----------------------------------")
    preference = df.pivot_table(index="爱好", columns="名称", values="喜爱程度")
    print("pivot_table", preference)
    # min_periods表示最小数据量，小于min_periods将不被计算
    corr_ = preference.corr(method="pearson", min_periods=1)
    print("corr", corr_)
    wind = corr_["wind"].drop(index="wind")
    # 获取相关系数最大的那个索引
    mostSimilar = wind.idxmax()
    print(wind)
    print("-------------------")
    print(mostSimilar)
    targetService = preference[mostSimilar]
    targetService = targetService[targetService.values >= 3]  # 假定评分大于3的才有值得推荐
    targetServiceName = targetService.index
    print(targetServiceName)
    print("------------------------")
    noNeed = preference["wind"].dropna().index  # 去除空值（没评分），即wind已经体验过的就不再推荐了
    print(noNeed)
    print("------------------------")
    recommend = targetServiceName[~targetServiceName.isin(noNeed)].values
    print("推荐", recommend)
    print("-----------------------------基于用户的协同过滤----------------------------------")

    print("-----------------------------基于物品的协同过滤----------------------------------")
    preference = df.pivot_table(index="名称", columns="爱好", values="喜爱程度")
    print("preference", preference)
    # 计算不同服务的相似程度（皮尔森相关系数）
    corr_ = preference.corr(method="pearson", min_periods=1)
    print("corr", corr_)
    # 获取wind评分过的爱好
    wind = preference.loc["wind"].dropna()
    # 获取wind评分过的爱好以及相应的评分
    service_wind = wind.index
    serviceRate_wind = wind.values
    print("service_wind", service_wind)
    print("serviceRate_wind", serviceRate_wind)
    # 获取wind评分过的爱好和他没评分过的爱好的皮尔森相关系数
    similarService = corr_[service_wind].drop(index=service_wind)
    print("similarService", similarService)
    # 计算wind对他没评分过的服务的感兴趣程度
    product = serviceRate_wind * similarService
    print("product", similarService)
    tendToPrefer = product.sum(axis=1)
    # 递减排序,取最高的那个
    tendToPrefer = tendToPrefer.sort_values(ascending=False)
    recommend = tendToPrefer.index[0:1].values
    print("推荐", recommend)
    print("-----------------------------基于物品的协同过滤----------------------------------")
